{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "a807c4c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "import matplotlib.pyplot as plt\n",
    "from sklearn.datasets import load_iris\n",
    "from sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\n",
    "from sklearn.linear_model import LogisticRegression as LR\n",
    "from sklearn.preprocessing import StandardScaler\n",
    "from sklearn import metrics"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e4d3bcd5",
   "metadata": {},
   "source": [
    "### 导入数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "a56a1400",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(150, 4)\n",
      "(150,)\n"
     ]
    }
   ],
   "source": [
    "data = load_iris()\n",
    "x = data.data\n",
    "y = data.target\n",
    "print(x.shape)\n",
    "print(y.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "10f9d1bd",
   "metadata": {},
   "source": [
    "### 切分数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "15a82bbf",
   "metadata": {},
   "outputs": [],
   "source": [
    "#划分数据集\n",
    "Xtrain, Xtest, Ytrain, Ytest = train_test_split(x,y,test_size=0.3,random_state=420)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "f8559bc8",
   "metadata": {},
   "source": [
    "### 使用标准化包，对训练集来学习，从而对训练集和测试集来做标准化"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "4423320c",
   "metadata": {},
   "outputs": [],
   "source": [
    "#对训练集和测试集做标准化---去量纲\n",
    "std = StandardScaler().fit(Xtrain)\n",
    "Xtrain_ = std.transform(Xtrain)\n",
    "Xtest_ = std.transform(Xtest)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "17298930",
   "metadata": {},
   "source": [
    "### 在确定l2范式的情况下，使用网格搜索判断solver, C的最优组合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "052376b0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "GridSearchCV(cv=5, estimator=LogisticRegression(max_iter=10000),\n",
       "             param_grid={'C': [0.05, 0.10277777777777777, 0.15555555555555556,\n",
       "                               0.20833333333333331, 0.2611111111111111,\n",
       "                               0.3138888888888889, 0.36666666666666664,\n",
       "                               0.41944444444444445, 0.4722222222222222, 0.525,\n",
       "                               0.5777777777777778, 0.6305555555555556,\n",
       "                               0.6833333333333333, 0.7361111111111112,\n",
       "                               0.788888888888889, 0.8416666666666667,\n",
       "                               0.8944444444444445, 0.9472222222222223, 1.0],\n",
       "                         'solver': ['liblinear', 'sag', 'newton-cg', 'lbfgs']})"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#在l2范式下，判断C和solver的最优值\n",
    "p = {\n",
    "    'C':list(np.linspace(0.05,1,19)),\n",
    "    'solver':['liblinear','sag','newton-cg','lbfgs']\n",
    "}\n",
    "\n",
    "model = LR(penalty='l2',max_iter=10000)\n",
    "\n",
    "GS = GridSearchCV(model,p,cv=5)\n",
    "GS.fit(Xtrain_,Ytrain)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "8cb81e21",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.9714285714285715"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GS.best_score_"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "12d633d8",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'C': 0.41944444444444445, 'solver': 'sag'}"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "GS.best_params_"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4a3c70ce",
   "metadata": {},
   "source": [
    "### 将最优的结果重新用来实例化模型，查看训练集和测试集下的分数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "df7eb5a7",
   "metadata": {},
   "outputs": [],
   "source": [
    "#将最优参数重新用于实例化模型，查看训练集和测试集下的分数\n",
    "model = LR(penalty='l2',\n",
    "           max_iter=10000,\n",
    "           C=GS.best_params_['C'],\n",
    "           solver=GS.best_params_['solver'])  #sag 三种通过导数计算的方式是不能l1正则化的"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "6515f7b9",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "LogisticRegression(C=0.41944444444444445, max_iter=10000, solver='sag')"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.fit(Xtrain_,Ytrain)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "id": "029a9632",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(0.9714285714285714, 0.9555555555555556)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.score(Xtrain_,Ytrain),model.score(Xtest_,Ytest)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0bbfb36f",
   "metadata": {},
   "source": [
    "### 计算精准率"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "70aec188",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "精准率: 0.22\n"
     ]
    }
   ],
   "source": [
    "Y_pred = model.predict(Xtest)\n",
    "print(\"精准率: {:.2f}\".format(metrics.accuracy_score(Ytest,Y_pred)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "50d3832d",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.5"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": false
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
